const express = require('express');
const md5 = require('md5');
const userModel = require('../db/models/userModel');
const { signToken, verifyToken } = require('../utils/tokenUtil');

const router = express.Router();

// 登录接口
router.post('/login', async(req, res) => {

    // 获取请求体
    let { username, pwd } = req.body;

    // 验证账号和密码
    // 数据库
    let user = await userModel.findOne({ username, pwd: md5(pwd) });

    // console.log(data);

    if (user) {
        // res.send('登录成功')
        console.log(user);

        // 生成token
        let token = signToken({
            name: user.username
        })

        res.json({
            code: "2000",
            data: {
                user,
                token: token
            },
            message: "登陆请求成功"
        })

    } else {
        // res.send('账号密码错误')
        res.json({
            code: "2001",
            message: "账号密码错误，请检查"
        })
    }


    // res.send('ok');

})

// 获取登录用户接口
router.get('/info', async(req, res) => {

    // 获取数据 - 数据库
    // 获取请求头 - token - name = useranme
    // console.log(req.headers.token);
    // res.send('ok');

    try {
        let data = await verifyToken(req.headers.token);
        let user = await userModel.findOne({ username: data.name });

        res.json({
            code: 2000,
            data: user,
            message: "获取用户信息成功"
        })
    } catch (err) {
        res.json({
            code: 2002,
            message: "请检查token是否合法"
        })
    }

})

// 退出登录
router.get('/logout', (req, res) => {
    res.json({
        code: 2000,
        message: "退出登录成功"
    })
})


module.exports = router;